class AssistancesController < ApplicationController
  layout "application", :except => :screen_control
  protect_from_forgery :only => [:create, :destroy, :update]
  
  def index
    if params[:client_id]
      @assistances = Assistance.find(:all, :conditions => ["client_id = ?", params[:client_id]], 
                                :order => 'created_at DESC').paginate :per_page => 10, :page => params[:page]
    else
      @assistances = Assistance.find(:all, :include => :client, 
                                :order => 'assistances.created_at DESC').paginate :per_page => 10, 
                                :page => params[:page]
    end

    respond_to do |format|
      format.html
      format.xml  { render :xml => @assistances }
    end
  end

  def screen_control
    @today = Assistance.find(:all, :include => :client, 
                             :conditions => ['expiration > ? AND ticket_state != ?', Time.now, 2], 
                             :order => "expiration ASC", :limit => 100 )
                             
    @expired = Assistance.find(:all, :include => :client, 
                               :conditions => ['expiration < ? AND ticket_state != ?', Time.now, 2], 
                               :order => "expiration ASC", :limit => 100 )
    
    respond_to do |format|
      format.html
      format.xml  { render :xml => @assistances }
    end
  end

  def todo
    stato = params[:id]
    @assistances = Assistance.find_all_by_ticket_state(stato, 
                              :order => 'created_at DESC').paginate :per_page => 10, :page => params[:page]
    
    @titolo = case
      when stato == "0": "non complete"
      when stato == "1": "parziali"
    end
    
    respond_to do |format|
      format.html
      format.xml  { render :xml => @assistances }
    end
  end

  def urgent
    @assistances = Assistance.find_all_by_urgency(params[:id], :order => 'expiration DESC').paginate :per_page => 10, 
                              :page => params[:page]
    
    respond_to do |format|
      format.html
      format.xml  { render :xml => @assistances }
    end
  end

  def show
    @assistance = Assistance.find(params[:id])

    respond_to do |format|
      format.html
      format.xml  { render :xml => @assistance }
    end
  end
  
  def send_resoconto_client
    @assistance = Assistance.find(params[:id])
    
    if Postoffice.deliver_resoconto(client_find, @assistance, false)
      @assistance.confirm = 1
      @assistance.save
    end
    
    respond_to do |format|
      flash[:notice] = "Il resoconto è stato inviato."
      format.html { redirect_to(@assistance) }
      format.xml  { head :ok }
    end
  end
  
  def send_resoconto_intern
    @assistance = Assistance.find(params[:id])
    
    Postoffice.deliver_resoconto(client_find, @assistance, true)
    
    respond_to do |format|
      flash[:notice] = "Il resoconto è stato inviato."
      format.html { redirect_to(@assistance) }
      format.xml  { head :ok }
    end
  end
  
  def preview_resoconto
    @assistance = Assistance.find(params[:id])
    @client = client_find
  end

  def new
    @assistance = Assistance.new
    @assistance.client_id = params[:id]
    
    respond_to do |format|
      if params[:id]
        format.html
        format.xml  { render :xml => @assistance }
      else
        flash[:alert] = 'Non è possibile creare un Assistenza se non associata ad un cliente.'
        format.html {redirect_to clients_path}
      end
    end
  end

  def edit
    @assistance = Assistance.find(params[:id])
  end

  def create
    @assistance = Assistance.new(params[:assistance])
    
    @assistance.num_ass = numero_assistenza(@assistance.client_id)
    
    @globe = false #TODO: Migliorare cattura valore globe
    @globe = true if params[:globe]
    
    respond_to do |format|
      if @assistance.save
        flash[:notice] = 'Assistenza creata con successo.'
        
        invio_resoconto
        
        format.html { redirect_to(@assistance) }
        format.xml  { render :xml => @assistance, :status => :created, :location => @assistance }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @assistance.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    params[:assistance][:operation_ids] ||= []
    @assistance = Assistance.find(params[:id])

    respond_to do |format|
      if @assistance.update_attributes(params[:assistance])
        flash[:notice] = 'Assistenza aggiornata con successo.'
        format.html { redirect_to(@assistance) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @assistance.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @assistance = Assistance.find(params[:id])
    @assistance.destroy

    respond_to do |format|
      format.html { redirect_to :back }
      format.xml  { head :ok }
    end
  end
  
  protected

    def invio_resoconto
      if @globe
        client = client_find.name_or_society
        if !@assistance.typology.blank?
          Postoffice.deliver_open_ticket(client, @assistance)
          flash[:notice] << "<br />Mail inviata a Globe."
        else
          flash[:alert] = "Non è stato selezionato il Tipo. Mail a globe non inviata. "
          flash[:alert] << "<br />Provvedere all'invio manualmente: <br />"
          flash[:alert] << "# tipo - [" + client + "] - " + @assistance.short_desc + ""
        end
      end
    end
  
    def client_find
      Client.find(@assistance.client_id)
    end
    
    def numero_assistenza(id)
      last = Assistance.find(:first, :conditions => ['client_id = ?', id], :order => "created_at DESC")
      if last
        last.num_ass + 1
      else
        return 1
      end
    end
  
end
